package a51qindian.com.comprehensive.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.li.utils.ToastUtil;
import com.li.widget.MultipleLayout;
import com.li.widget.PersonalDetailItem;
import com.li.widget.TopNavigationBar;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import a51qindian.com.comprehensive.R;
import a51qindian.com.comprehensive.base.QDBaseActivity;
import a51qindian.com.comprehensive.net.ObservableHelper;
import a51qindian.com.comprehensive.net.RetrofitCreator;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;


public class FinishInstallActivity extends QDBaseActivity {

    @BindView(R.id.top_navigation)
    TopNavigationBar mTopNavigation;
    @BindView(R.id.txt_shop_name)
    PersonalDetailItem mTxtShopName;
    @BindView(R.id.txt_sn)
    PersonalDetailItem mTxtSn;
    @BindView(R.id.txt_address)
    PersonalDetailItem mTxtAddress;
    @BindView(R.id.layout_content)
    MultipleLayout mLayoutContent;
    //纬度
    private String mLat;
    //经度
    private String mLng;
    //声明mLocationClient对象
    public AMapLocationClient mLocationClient;
    //声明mLocationOption对象
    public AMapLocationClientOption mLocationOption = null;
    private String mTid;
    private int mPos;
    private int mNumber;
    private static final int REQUEST_INSTALL__SN_CODE = 1000;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_finish_install;
    }

    @Override
    protected void initSth() {
        super.initSth();
        mTopNavigation.setNavigationBarListener(this);
        String type = getIntent().getStringExtra("type");
        mTid = getIntent().getStringExtra("tid");
        mPos = getIntent().getIntExtra("pos", -1);
        String shopName = getIntent().getStringExtra("shopName");
        mNumber = Integer.parseInt(getIntent().getStringExtra("number"));
        switch (type) {
            case "0":
                mTopNavigation.setTitle("首装任务");
                break;
            case "1":
                mTopNavigation.setTitle("加装任务");
                break;
        }
        mTxtShopName.setTxtRight(shopName);

        if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) ==
                PackageManager.PERMISSION_DENIED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
        }
        mTxtSn.getRightTextView().setMaxLines(10);
        mTxtSn.getRightTextView().setMovementMethod(ScrollingMovementMethod.getInstance());
        mTxtSn.getRightTextView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, QRCodeActivity.class);
                intent.putExtra("source", "install");
                startActivityForResult(intent, REQUEST_INSTALL__SN_CODE);
            }
        });
    }

    @OnClick({R.id.txt_sn, R.id.txt_address, R.id.btn_confirm})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.txt_sn:
                Intent intent = new Intent(mContext, QRCodeActivity.class);
                intent.putExtra("source", "install");
                startActivityForResult(intent, REQUEST_INSTALL__SN_CODE);

                break;
            case R.id.txt_address:
                getLatLng();
                break;
            case R.id.btn_confirm:
                String txt = mTxtSn.getTxtRightContent();
                if (txt.split("\\|").length != mNumber || TextUtils.isEmpty(txt)) {
                    showToast("安装设备数量为："+mNumber+"套，请检查安装数量");
                    return;
                }
                if (TextUtils.isEmpty(mLat)||TextUtils.isEmpty(mLng)) {
                    showToast("请先获取地址");
                    return;
                }
                finishTsk(mUid, mTid,
                        mTxtSn.getTxtRightContent(), mLat, mLng);
                break;
        }
    }

    /**
     * 获取经纬度
     */
    private void getLatLng() {
        mLayoutContent.onLoadingWithContent("正在获取当前位置信息");
        mLocationClient = new AMapLocationClient(mContext);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位监听
        mLocationClient.setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                if (aMapLocation != null) {
                    if (aMapLocation.getErrorCode() == 0) {
                        mLayoutContent.onSuccess();
                        //定位成功回调信息，设置相关消息
                        aMapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                        mLat = String.valueOf(aMapLocation.getLatitude());//获取纬度
                        mLng = String.valueOf(aMapLocation.getLongitude());//获取经度
                        aMapLocation.getAccuracy();//获取精度信息
                        mLocationClient.stopLocation();
                        mLocationClient.onDestroy();
                        mTxtAddress.setTxtRight(aMapLocation.getAddress());
                        Log.e("tag", "onLocationChanged: "+mLat+"|"+mLng);
                    } else {
                        mLocationClient.stopLocation();
                        mLayoutContent.onSuccess();
                        mLocationClient.onDestroy();
                        ToastUtil.showToast(mContext, "定位失败，请确保自己定位权限打开并重新提交任务");
                    }
                }
            }
        });
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000);
        //设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
        // 注意设置合适的定位时间的间隔（最小间隔支持为1000ms），并且在合适时间调用stopLocation()方法来取消定位请求
        // 在定位结束后，在合适的生命周期调用onDestroy()方法
        // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
        //启动定位
        mLocationClient.startLocation();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mLocationClient != null) {
            mLocationClient.onDestroy();
        }
    }

    /**
     * 完成任务
     *
     * @param uid 用户编号
     * @param tid 任务编号
     * @param sn  设备编号
     * @param lat 经度
     * @param lng 纬度
     */
    private void finishTsk(String uid, String tid, String sn, String lat, String lng) {
        Map<String, String> map = new HashMap<>();
        map.put("uid", uid);
        map.put("tid", tid);
        map.put("sn", sn);
        map.put("lat", lat);
        map.put("lng", lng);
        ObservableHelper.createObservable(RetrofitCreator.createService().doneInstallTask(map))
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        mLayoutContent.onSuccess();
                        try {
                            JSONObject object = new JSONObject(s);
                            int code = object.getInt("code");
                            showToast(object.getString("info"));
                            if (code == 1) {
                                Intent intent = new Intent();
                                intent.putExtra("pos", mPos);
                                setResult(RESULT_OK, intent);
                                finish();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        mLayoutContent.onSuccess();
                        ToastUtil.showToast(mContext, e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_INSTALL__SN_CODE && RESULT_OK == resultCode) {
            String sn = data.getStringExtra("sn");
            StringBuilder builder = new StringBuilder(mTxtSn.getTxtRightContent());
            String[] s = builder.toString().split("\\|");
            List<String> list = Arrays.asList(s);
            if (list.contains(sn)) {
                showToast("已添加过该设备号");
                return;
            }
            if (TextUtils.isEmpty(mTxtSn.getTxtRightContent())) {
                builder.append(sn);
            } else {
                builder.append(String.valueOf("|" + sn));
            }
            mTxtSn.setTxtRight(builder.toString());

        }
    }
}
